#include <cstdio>
#include <cstring>
#include <queue>
#include <set>
using namespace std;

//B:0 W:1 R:2 E:3
int ROT[3][4] = {{1, 1, 2, 2}, {0, 0, 2, 2}, {0, 0, 1, 1}};
int DIR[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

char MAP[3][3];
char FINAL[3][3];
int EX, EY;
int FX, FY;

struct Node {
    int c;
    int ex, ey;
    char M[3][3];
    Node(int c, int ex, int ey, char m[3][3]): c(c), ex(ex), ey(ey) {
        memcpy(M, m, 9*sizeof(char));
    }
};

int myhash(char M[3][3]) {
    int h = 0;
    for (int i=0; i<3; i++) {
        for (int j=0; j<3; j++) {
            h <<= 2;
            h |= M[i][j];
        }
    }
    return h;
}

void print(char M[3][3]) {
    for (int i=0; i<3; i++) {
        for (int j=0; j<3; j++) {
            char c;
            if (M[j][i] == 0) c = 'B';
            else if (M[j][i] == 1) c = 'W';
            else if (M[j][i] == 2) c = 'R';
            else c = 'E';
            printf("%c ", c);
        }
        printf("\n");
    }
    printf("\n");
}

bool check(char M[3][3], int ex, int ey) {
    if (ex != FX || ey != FY) return false;
    for (int i=0; i<3; i++) {
        for (int j=0; j<3; j++) {
            if (M[i][j] != FINAL[i][j])
                return false;
        }
    }
    return true;
}

int BFS() {
    queue<Node> q;
    set<int> vis;
    Node start = Node(0, EX, EY, MAP);
    q.push(start);
    vis.insert(myhash(MAP));
    while (!q.empty()) {
        Node n = q.front(); q.pop();
        print(n.M);
        if (check(n.M, n.ex, n.ey)) return n.c;
        if (n.c+1 > 30) continue;
        for (int i=0; i<4; i++) {
            int ex=n.ex, ey=n.ey;
            int mx=ex+DIR[i][0], my=ey+DIR[i][1];
            if (mx < 0 || mx >= 3 || my < 0 || my >= 3) continue;
            Node m = Node(n.c+1, mx, my, n.M);
            int ori = m.M[mx][my];
            m.M[ex][ey] = ROT[ori][i];
            m.M[mx][my] = 3;
            int h = myhash(m.M);
            if (!vis.count(h)) {
                q.push(m);
                vis.insert(h);
            }
        }
    }
    printf("FUCK!\n");
    return -1;
}

int main()
{
    while (scanf("%d%d", &EX, &EY), EX && EY) {
        EX--; EY--;
        char buf[5];
        for (int i=0; i<3; i++) {
            for (int j=0; j<3; j++) {
                scanf("%s", buf);
                int a=3;
                if (buf[0] == 'B') a=0;
                else if (buf[0] == 'W') a=1;
                else if (buf[0] == 'R') a=2;
                else if (buf[0] == 'E') {
                    FX = j; FY = i;
                }
                FINAL[j][i] = a;
                if (j == EX && i == EY) {
                    MAP[j][i] = 3;
                } else {
                    MAP[j][i] = 1;
                }
            }
        }
//        print(MAP);
//        print(FINAL);
        if (check(MAP, EX, EY)) {
            printf("0\n");
            continue;
        }
        int ans = BFS();
        printf("%d\n", ans);
    }
    return 0;
}
